﻿#include "stdafx.h"
#include "FileUtils.h"

namespace FileUtils
{
	void SplitPath(const TCHAR *path, TCHAR *drive,
		TCHAR *dir, TCHAR *fname, TCHAR *ext)
	{
#ifdef UNICODE
		return _wsplitpath(path, drive, dir, fname, ext);
#else
		return _splitpath(path, drive, dir, fname, ext);
#endif
	}


	CString GetFileName(const TCHAR *path, bool bIncludeExt/* = false*/)
	{
		TCHAR *pfname = NULL, *pext = NULL;
		SplitPath(path, NULL, NULL, pfname, pext);

		if (bIncludeExt)
		{
			return CString(pfname) + CString(pext);
		}
		else
		{
			return CString(pfname);
		}
	}

	CString GetFilePath(const TCHAR *path)
	{
		TCHAR *pdrive = NULL, *pdir = NULL;
		SplitPath(path, pdrive, pdir, NULL, NULL);

		return CString(pdrive) + CString(pdir);
	}

	CodingForm GetFileCodingForm(LPCTSTR lpFilePath)
	{
		if (lpFilePath == NULL)
		{
			return eUnableJudge;
		}

		wifstream fin(lpFilePath, ios::binary);

		unsigned char s1;
		fin.read((char*)&s1, sizeof(s1)); // 读第一个字节
		int p = s1 << 8; // 左移8位
		fin.read((char*)&s1, sizeof(s1)); // 读第二个字节
		p |= s1; // 

		CodingForm codingForm = eUnableJudge;
		switch (p)
		{
		case 0xFFFE:
			codingForm = eUnicode;
			break;
		case 0xFEFF:
			codingForm = eUnicodeBigEndian;
			break;
		case 0xEFBB:
			codingForm = eUTF_8;
			break;
		default:
		{
			unsigned long countGBK = 0;
			break;
		}
		}

		fin.close();
		return codingForm;
	}

	unsigned long GetCountGBK(const char* str, unsigned long strLength)
	{
		unsigned long counter = 0;
		const unsigned char head = 0x80;
		unsigned char firstChar, secondChar;

		for (unsigned long i = 0; i < strLength - 1; ++i)
		{
			firstChar = (unsigned char)str[i];
			if (!(firstChar & head))
				continue;

			secondChar = (unsigned char)str[i];
			if (firstChar >= 161 && firstChar <= 247 && secondChar >= 161 && secondChar <= 254)
			{
				counter += 2;
				++i;
			}
		}
		return counter;
	}

	unsigned long GetCountUTF_8(const char* str, unsigned long strLength)
	{
		unsigned long counter = 0;
		unsigned char head = 0x80;
		unsigned char firstChar;
		for (unsigned long i = 0; i < strLength; ++i)
		{
			firstChar = (unsigned char)str[i];
			if (!(firstChar & head))
				continue;

			unsigned char tmpHead = head;
			unsigned int wordLen = 0, tPos = 0;
			while (firstChar & tmpHead)
			{
				++wordLen;
				tmpHead >>= 1;
			}

			if (wordLen <= 1)
				continue; //utf8最小长度为2  

			wordLen--;
			if (wordLen + i >= strLength)
				break;

			for (tPos = 1; tPos <= wordLen; ++tPos)
			{
				unsigned char secondChar = (unsigned char)str[i + tPos];
				if (!(secondChar & head))
					break;
			}

			if (tPos > wordLen)
			{
				counter += wordLen + 1;
				i += wordLen;
			}
		}

		return counter;
	}
}


